//
//  M_MineCoreViewController.m
//  Model
//
//  Created by apple on 2018/7/10.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "M_MineCoreViewController.h"
#import "UIButton+AddAction.h"
#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "ICN_HeadImageSelView.h"

#define NUM @"0123456789Xx"
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@interface M_MineCoreViewController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate, STPhotoKitDelegate>
{
    UIView *grayView;//相册
    UIView *xingBieView;//性别
}
@property (nonatomic, strong) UIButton *headBtn;//头像
@property (nonatomic, strong) UITextField *zhangHaoTF;
@property (nonatomic, strong) UIButton *xingBieBtn;//性别
@property (strong, nonatomic) ICN_HeadImageSelView *changeHeadImageView;
@property (nonatomic, strong) NSData *imageData;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImageView *headImgView;//头像
@property (nonatomic, strong) NSMutableDictionary *dataDic;
@end

@implementation M_MineCoreViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self data];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    
}
#pragma mark - ---------- 懒加载 ----------
- (ICN_HeadImageSelView *)changeHeadImageView {
    if (!_changeHeadImageView)
    {
        _changeHeadImageView = [[NSBundle mainBundle] loadNibNamed:@"ICN_HeadImageSelView" owner:self options:nil].lastObject;
    }
    return _changeHeadImageView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人中心";
    [self creationView];
    // Do any additional setup after loading the view.
}
- (NSMutableDictionary *)dataDic{
    
    if (!_dataDic) {
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
    
}
- (void)data{
    
    //    self.dataDic = [NSMutableDictionary dictionary];
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    [productParams setValue:token forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:UserInfo networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        
        if ([[returnData objectForKey:@"Status"]intValue]==200) {
            
            self.dataDic = returnData[@"Data"];
            NSLog(@"%@", self.dataDic);
            self.zhangHaoTF.text = [self.dataDic objectForKey:@"username"];
            [self.headImgView sd_setImageWithURL:[NSURL URLWithString:[self.dataDic objectForKey:@"headpicture"] ] placeholderImage:[UIImage imageNamed:@"headmoren"]];
            if ([[self.dataDic objectForKey:@"sex"] integerValue] == 0) {
                [self.xingBieBtn setTitle:@"女" forState:UIControlStateNormal];
            }else{
                [self.xingBieBtn setTitle:@"男" forState:UIControlStateNormal];
            }
            
        }
        
        else {
            
            //            [PublicFunction showAlert:nil message:[returnData objectForKey:@"Msg"] duration:5.0f];
            
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        
    }];
    
    
    
}
- (void)creationView{
    
    self.headImgView = [[UIImageView alloc] init];
    [self.view addSubview:self.headImgView];
    [self.headImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(20);
        make.centerX.equalTo(self.view);
        make.width.offset(120);
        make.height.offset(120);
        
    }];
    self.headImgView.layer.cornerRadius = 60;
    self.headImgView.layer.masksToBounds = YES;
    
    
    self.headBtn = [[UIButton alloc] init];
    [self.view addSubview:self.headBtn];
    [self.headBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(20);
        make.centerX.equalTo(self.view);
        make.width.offset(120);
        make.height.offset(120);
        
    }];
//    [self.headBtn setImage:[UIImage imageNamed:@"photo_head"] forState:UIControlStateNormal];
    self.headBtn.backgroundColor = [UIColor clearColor];
    [self.headBtn addTarget:self action:@selector(headClick) forControlEvents:UIControlEventTouchUpInside];
    self.headBtn.layer.cornerRadius = 60;
    self.headBtn.layer.masksToBounds = YES;
    
    
    UIImageView *zhangHaoImgView = [[UIImageView alloc] init];
    [self.view addSubview:zhangHaoImgView];
    [zhangHaoImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headBtn.mas_bottom).with.offset(20);
        make.left.equalTo(self.view).with.offset(38);
        make.right.equalTo(self.view).with.offset(-38);
        make.height.offset(44);
    }];
    
    zhangHaoImgView.image = [UIImage imageNamed:@"line_frame"];
    zhangHaoImgView.userInteractionEnabled = YES;
    
    UIImageView *zhangHaoIcon = [[UIImageView alloc] init];
    [zhangHaoImgView addSubview:zhangHaoIcon];
    UIImage *zhangHaoIconImg =[UIImage imageNamed:@"icon_my_p"];
    [zhangHaoIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zhangHaoImgView).with.offset(16);
        make.centerY.equalTo(zhangHaoImgView);
        make.width.offset(zhangHaoIconImg.size.width);
        make.height.offset(zhangHaoIconImg.size.height);
    }];
    zhangHaoIcon.image = [UIImage imageNamed:@"icon_my_p"];
    
    UIView *zhangHaoLine = [[UIView alloc] init];
    [zhangHaoImgView addSubview:zhangHaoLine];
    [zhangHaoLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zhangHaoIcon.mas_right).with.offset(8);
        make.height.offset(14);
        make.width.offset(1);
        make.centerY.equalTo(zhangHaoIcon);
        
    }];
    zhangHaoLine.backgroundColor = getColor(@"ff40c6");
    
    self.zhangHaoTF = [[UITextField alloc] init];
    [zhangHaoImgView addSubview:self.zhangHaoTF];
    [self.zhangHaoTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zhangHaoIcon.mas_right).with.offset(17);
        make.right.equalTo(zhangHaoImgView).with.offset(-16);
        make.centerY.equalTo(zhangHaoIcon);
    }];
    self.zhangHaoTF.placeholder = @"请输入昵称";
    self.zhangHaoTF.font = [UIFont systemFontOfSize:14];
    self.zhangHaoTF.textColor = getColor(@"ff40c6");
    self.zhangHaoTF.delegate = self;
    
    /////性别
    UIImageView *miMaImgView = [[UIImageView alloc] init];
    [self.view addSubview:miMaImgView];
    [miMaImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(zhangHaoImgView.mas_bottom).with.offset(16);
        make.left.equalTo(self.view).with.offset(38);
        make.right.equalTo(self.view).with.offset(-38);
        make.height.offset(44);
    }];
    
    miMaImgView.image = [UIImage imageNamed:@"line_frame"];
    miMaImgView.userInteractionEnabled = YES;
    
    UIImageView *miMaIcon = [[UIImageView alloc] init];
    [miMaImgView addSubview:miMaIcon];
    UIImage *miMaIconImg =[UIImage imageNamed:@"icon_sex"];
    [miMaIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(miMaImgView).with.offset(16);
        make.centerY.equalTo(miMaImgView);
        make.width.offset(miMaIconImg.size.width);
        make.height.offset(miMaIconImg.size.height);
    }];
    miMaIcon.image = [UIImage imageNamed:@"icon_sex"];
    
    UIView *miMaLine = [[UIView alloc] init];
    [miMaImgView addSubview:miMaLine];
    [miMaLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(miMaIcon.mas_right).with.offset(8);
        make.height.offset(14);
        make.width.offset(1);
        make.centerY.equalTo(miMaIcon);
        
    }];
    miMaLine.backgroundColor = getColor(@"ff40c6");
    
    self.xingBieBtn = [[UIButton alloc] init];
    [miMaImgView addSubview:self.xingBieBtn];
    [self.xingBieBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(miMaIcon.mas_right).with.offset(17);
        make.right.equalTo(miMaImgView).with.offset(-16);
        make.centerY.equalTo(miMaIcon);
    }];
    self.xingBieBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.xingBieBtn setTitleColor:getColor(@"ff40c6") forState:UIControlStateNormal];
    self.xingBieBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [self.xingBieBtn addTarget:self action:@selector(xingBieClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    self.xingBieBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    ///完成
    UIButton *phoneBtn = [[UIButton alloc] init];
    [self.view addSubview:phoneBtn];
    [phoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(38);
        make.right.equalTo(self.view).with.offset(-38);
        make.top.equalTo(miMaImgView.mas_bottom).with.offset(44);
        make.height.offset(44);
    }];
    
    [phoneBtn setBackgroundImage:[UIImage imageNamed:@"bg_button_2"] forState:UIControlStateNormal];
    [phoneBtn setTitle:@"完成" forState:UIControlStateNormal];
    
    [phoneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    phoneBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    
    [phoneBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *huiLine = [[UIView alloc] init];
    [self.view addSubview:huiLine];
    [huiLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneBtn.mas_bottom).with.offset(13);
        make.centerX.equalTo(self.view);
        make.width.offset(1);
        make.height.offset(12);
        
    }];
    
    
    
    
}
/////完成
- (void)loginClick{
 
    if (self.zhangHaoTF.text.length == 0) {
        
        [PublicFunction showAlert:nil message:@"请补全信息" duration:10.0f];
        return;
    }
    
    
        //两种方式上传头像
        /*方式一：使用NSData数据流传图片*/
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        //
        
        NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
        NSString *token = [PublicFunction getConfigWithKey:@"token"];
        [productParams setValue:token forKey:@"token"];
        [productParams setValue:self.zhangHaoTF.text forKey:@"nickname"];
        NSString *gender;
        if ([self.xingBieBtn.titleLabel.text isEqualToString:@"男"]) {
            gender = @"1";
        }else{
            gender = @"0";
        }
        [productParams setValue:gender forKey:@"gender"];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/plain",
                                                             @"text/javascript",
                                                             @"text/json",
                                                             @"text/html",
                                                             @"image/jpeg", nil];
        [manager POST:changeheadimg parameters:productParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            if (self.image) {

                self.imageData = UIImageJPEGRepresentation(self.image,0.005);
                
            }else {

                self.imageData = UIImageJPEGRepresentation(self.headImgView.image,0.005);
 
            }
         
            
            //压缩图片
            
            //拼接图片名称+时间确保不重复命名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *imageFileName = [NSString stringWithFormat:@"%@.jpg", [formatter stringFromDate:[NSDate date]]];
            // 测试输出文件名
            
            //上传图片，以文件流的格式sdf
            
            //        [formData appendPartWithFileData:UIImageJPEGRepresentation([UIImage imageNamed:@"1"], 5.0) name:@"image1" fileName:@"1.jpg" mimeType:@"image/jpeg"];
            
            [formData appendPartWithFileData:self.imageData name:@"file" fileName:imageFileName mimeType:@"image/jpeg"];
            
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSString *strtmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSString *requestTmp = [NSString stringWithString: strtmp];
            NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];  //解析
            
            //        [self.navigationController popToRootViewControllerAnimated:YES];
            
            [self.navigationController popViewControllerAnimated:YES];
            
            
            NSLog(@"+++>%@", resultDic);
            
            NSLog(@"--->%@", resultDic[@"Msg"]);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            
            NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"服务器的错误原因:%@",str);
            
            
            NSLog(@"--->%@", error);
        }];
   
    
    
}
- (void)headClick{
    [self.zhangHaoTF resignFirstResponder];
    
    [self editImageSelected];
}
- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    [self.headBtn setImage:resultImage forState:UIControlStateNormal];
    

    
    self.image = resultImage;
    //    self.shoppicImage.image = resultImage;
    
    self.headImgView.image = resultImage;
    
}
#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        
        [photoVC setSizeClip:CGSizeMake(120, 120)];
        
        
        [self presentViewController:photoVC animated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - --- event response 事件相应 ---
- (void)editImageSelected
{
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
    
    [[UIApplication sharedApplication].keyWindow addSubview:grayView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
    [grayView addGestureRecognizer:tapGesture];
    
    [grayView addSubview:self.changeHeadImageView];
    [self.changeHeadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(DEF_SCREEN_WIDTH, 111));
    }];
    
    //    self.changeHeadImageView.layer.cornerRadius = 8;
    [self.changeHeadImageView.takePhotoButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        [grayView removeFromSuperview];
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
            NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
        }
    }];
    [self.changeHeadImageView.localAlbumButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [controller setDelegate:self];
        [grayView removeFromSuperview];
        if ([controller isAvailablePhotoLibrary]) {
            [self presentViewController:controller animated:YES completion:nil];
        }
    }];
    [self.changeHeadImageView.closeViewButton addAction:^(NSInteger tag) {
        [self dismissContactView];
    }];
}

#pragma mark ---------------- 选择性别
- (void)xingBieClick{
    [self.zhangHaoTF resignFirstResponder];
    xingBieView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    xingBieView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
    
    [[UIApplication sharedApplication].keyWindow addSubview:xingBieView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissXBView)];
    [xingBieView addGestureRecognizer:tapGesture];
    
    UIView *changeView = [[UIView alloc] init];
    [xingBieView addSubview:changeView];
    [changeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(100);
        
    }];
    changeView.backgroundColor = [UIColor whiteColor];
    changeView.layer.cornerRadius = 5;
    changeView.layer.masksToBounds = YES;
    
    UIButton *nanBtn = [[UIButton alloc] init];
    [changeView addSubview:nanBtn];
    [nanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(changeView);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(50);
        
    }];
    [nanBtn setTitle:@"男" forState:UIControlStateNormal];
    [nanBtn setTitleColor:getColor(@"ff40c6") forState:UIControlStateNormal];
    nanBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [nanBtn addTarget:self action:@selector(nanClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    UIView *lineView = [[UIView alloc] init];
    [changeView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(1);
        make.bottom.equalTo(nanBtn.mas_top);
        
    }];
    lineView.backgroundColor = getColor(@"f7f7f7");
    
    UIButton *nvBtn = [[UIButton alloc] init];
    [changeView addSubview:nvBtn];
    [nvBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(changeView);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(50);
        
    }];
    [nvBtn setTitle:@"女" forState:UIControlStateNormal];
    [nvBtn setTitleColor:getColor(@"ff40c6") forState:UIControlStateNormal];
    nvBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [nvBtn addTarget:self action:@selector(nvClick) forControlEvents:UIControlEventTouchUpInside];
    
}
//男
- (void)nanClick{
    [xingBieView removeFromSuperview];
    [self.xingBieBtn setTitle:@"男" forState:UIControlStateNormal];
}
//女
- (void)nvClick{
    [xingBieView removeFromSuperview];
    [self.xingBieBtn setTitle:@"女" forState:UIControlStateNormal];
}
- (void)dismissXBView{
    
    [xingBieView removeFromSuperview];
    
    
}

- (void)dismissContactView {
    [grayView removeFromSuperview];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
